<script setup lang="ts">
import { ref, onUnmounted, nextTick } from "vue"
import { obsDownload } from '#/utils/obs'

import * as pdfjsLib from 'pdfjs-dist';
import 'pdfjs-dist/web/pdf_viewer.css';

defineOptions({ name: 'Dialog' })

const dialogVisible = ref(false)
const pdfLoading = ref(false);
const fileName = ref()
const certifiInfo = ref<any>()
const pdfContainer = ref<any>();
const currentPage = ref(1);
const totalPages = ref(0);
let pdf: any;

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  '#/utils/pdf.worker.min.js',
  import.meta.url,
).href;


const handleClose = () => {
  dialogVisible.value = false
}

const loadPdf = async (arraybuffer?: any) => {
  if (!pdfContainer.value) return;
  pdfLoading.value = true;
  try {
    pdf = await pdfjsLib.getDocument(arraybuffer).promise;
    totalPages.value = pdf.numPages;
    const renderPage = async (pageNumber: number) => {
      const page = await pdf.getPage(pageNumber);
      const canvas = document.createElement('canvas');
      const viewport = page.getViewport({ scale: 1 });
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      const renderContext: any = {
        canvasContext: canvas.getContext('2d'),
        viewport,
      };
      await page.render(renderContext).promise;
      pdfContainer.value.innerHTML = '';
      pdfContainer.value.append(canvas);
    };
    await renderPage(currentPage.value);
  } catch (error) {
    console.error('加载 PDF 时出错:', error);
  }
  pdfLoading.value = false;
};

const inint = (data: any) => {
  dialogVisible.value = true
  nextTick(() => {
    certifiInfo.value = data.path
    fileName.value = data.fileName
    loadPdf(data.url)
  })
}

const handlerPdf = async (handleType: any) => {
  obsDownload({
    Key: certifiInfo.value,
  }, (err: any, result: any) => {
    if (err) {
      console.error('获取失败:', err);
      return;
    }
    const blob = new Blob([result.InterfaceResult.Content], {type: 'application/pdf'});

    // 生成并下载PDF
    if (handleType === 'DOWNLOAD') {
      // 创建Blob对象并触发下载
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName.value; // 可自定义下载文件名
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url); // 清理内存
    }
    // 生成并打印PDF
    if (handleType === 'PRINT') {
      const pdfUrl = URL.createObjectURL(blob);
      // 打开新窗口并触发打印
      const printWindow = window.open(pdfUrl);
      printWindow?.addEventListener('load', () => {
        printWindow.print();
      });
    }
  })
}
onUnmounted(() => {
  // 清理资源
  if (pdfContainer.value) {
    pdfContainer.value?.destroy();
    pdfContainer.value = null;
  }
});

defineExpose({ inint })

</script>
<template>
  <el-dialog v-model="dialogVisible" align-center :destroy-on-close="true" :title="$t('common.viewTxt')" :append-to-body="true"
    :close-on-click-modal="false" :before-close="handleClose">
    <div v-loading="pdfLoading" class="w-full pl-[15px] pr-[15px] pt-[10px] pb-[10px] ">
      <div class="w-full" ref="pdfContainer" id="pdfContainer"></div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handlerPdf('PRINT')">
          {{ $t('common.printTxt') }}
        </el-button>
        <el-button type="primary" @click="handlerPdf('DOWNLOAD')">
          {{ $t('common.downloadTxt') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
  #pdfContainer {
    :deep(canvas) {
      margin: 0 auto;
      border: 1px solid #eee;
    }
  }
</style>
